package com.example.home_model.details;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bw.ijk.widget.IjkView;
import com.example.baseadapter_sdk.BaseQuickAdapter;
import com.example.common.mvvm.view.BaseActivity;
import com.example.common.providerservice.CheckLoginAPI;
import com.example.home_model.R;
import com.example.home_model.databinding.ActivityDetailsBinding;
import com.example.home_model.details.entity.commententity.CommentDataDTO;
import com.example.home_model.entity.DataDTO;
import com.example.imageload_sdk.ImageLoad;
import com.tb.emoji.Emoji;
import com.tb.emoji.EmojiUtil;
import com.tb.emoji.FaceFragment;


import java.io.IOException;
import java.util.List;
import java.util.Map;

@Route(path = "/details/DetailsActivity")
public class DetailsActivity extends BaseActivity<ActivityDetailsBinding,DetailsViewModel>implements View.OnClickListener, BaseQuickAdapter.OnItemChildCLickListener, FaceFragment.OnEmojiClickListener {

    private DataDTO dataDTO;
    private int itemType;
    private TextView detailsText =null;
    private ImageView detailsImg = null;
    private IjkView detailsIjkView = null;
    private EditText commentEdit;
    private RadioButton addComment;
    private RecyclerView commentRc;
    private List<CommentDataDTO> commentlist;
    private RadioButton commentEmoji;
    private FaceFragment faceFragment;
    private FrameLayout container;

    private CheckLoginAPI checkLoginAPI;
    @Override
    public View bindLayout() {
        return v.getRoot();
    }

    @Override
    public ViewBinding initBind() {
        return ActivityDetailsBinding.inflate(inflater);
    }

    @Override
    public void initView() {
        checkLoginAPI = (CheckLoginAPI) ARouter.getInstance().build("/user/checklogin").navigation();
        itemType = dataDTO.itemType;
        switch (itemType){
            case 0:
                detailsText = v.detailsText;
                detailsText.setVisibility(View.VISIBLE);
                detailsText.setText(dataDTO.feeds_text);
                break;
            case 1:
                detailsImg = v.detailsImg;
                detailsImg.setVisibility(View.VISIBLE);
                ImageLoad.loadMatchImg(dataDTO.cover, detailsImg);
                break;
            case 2:
                detailsIjkView = v.detailsIjkView;
                detailsIjkView.setVisibility(View.VISIBLE);
                detailsIjkView.setPlayUrl(dataDTO.url, dataDTO.cover);
                break;
        }
        commentEdit = v.commentEdit;
        addComment = v.addComment;
        commentRc = v.commentRc;
        commentEmoji = v.commentEmoji;
        container = v.Container;


    }

    @Override
    public void initData() {
        addComment.setOnClickListener(this);
        vm.requestCommentList(dataDTO.itemId);
        commentEmoji.setOnClickListener(this);
        //初始化表情

        faceFragment = FaceFragment.Instance();
        getSupportFragmentManager().beginTransaction().add(R.id.Container, faceFragment).hide(faceFragment).commit();

    }

    @Override
    protected String pageName() {
        return "主页详情";
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        Intent intent = getIntent();
        dataDTO = (DataDTO) intent.getSerializableExtra("dataDTO");
        super.onCreate(savedInstanceState);

    }

    @Override
    public void receiveData(Map<String, Object> data) {
        String target = (String) data.get("target");
        if (target.equals("COMMENTLIST")){

            CommentAdapter adapter = (CommentAdapter) commentRc.getAdapter();
            if (adapter ==null){
                commentlist = (List<CommentDataDTO>) data.get("COMMENTLIST");
                adapter = new CommentAdapter();
                adapter.setOnItemChildCLickListener(this);
                commentRc.setLayoutManager(new LinearLayoutManager(commentRc.getContext(), RecyclerView.VERTICAL,false));
                commentRc.setAdapter(adapter);
                adapter.setNewInstance(commentlist);
            }else{
                commentlist =   (List<CommentDataDTO>) data.get("COMMENTLIST");
                adapter.getData().clear();
                adapter.setNewInstance(commentlist);
//                adapter.notifyDataSetChanged();
            }
        }
    }
    boolean flag =true;
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == addComment.getId()) {
            String string = commentEdit.getText().toString();
            vm.requestAddComment(dataDTO.itemId,string);

            commentEdit.setText("");
        }else if (id ==commentEmoji.getId()){
            if (flag){
                flag = !flag;

                getSupportFragmentManager().beginTransaction().show(faceFragment).commit();
                container.setVisibility(View.VISIBLE);

            }else {
                flag = !flag;
                getSupportFragmentManager().beginTransaction().hide(faceFragment).commit();
                container.setVisibility(View.INVISIBLE);
            }

        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, int id, int position) {
        if (id== R.id.itemCommentDel){
            if (!checkLoginAPI.checkLogin()){
                ARouter.getInstance().build("/user/LoginActivity").navigation();
                return;
            }
            long commentId = commentlist.get(position).commentId;
            vm.requestDelete(commentId,dataDTO.itemId);
        }
    }

    @Override
    public void onEmojiDelete() {
        String text = commentEdit.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                commentEdit.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                displayTextView();
                return;
            }
            commentEdit.getText().delete(index, text.length());
            displayTextView();
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        commentEdit.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        displayTextView();
    }


    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = commentEdit.getSelectionStart();
            Editable editable = commentEdit.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
        }
        displayTextView();
    }

    private void displayTextView() {
        try {
            EmojiUtil.handlerEmojiText(commentEdit, commentEdit.getText().toString(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
